package com.maila.xiaoaoschool.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.maila.xiaoaoschool.activity.LoginActivity;
import com.maila.xiaoaoschool.api.LoginApi;
import com.maila.xiaoaoschool.api.PrefApi;
import com.maila.xiaoaoschool.net.VolleyInterface;
import com.maila.xiaoaoschool.util.Constants;
import com.maila.xiaoaoschool.util.NullPointUtils;
import com.maila.xiaoaoschool.util.PrefUtil;
import com.orhanobut.logger.LogLevel;
import com.orhanobut.logger.Logger;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by mark on 2018/2/26.
 */

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    /**
     * 微信登录相关
     */
    private IWXAPI api;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //通过WXAPIFactory工厂获取IWXApI的示例
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID_WX,true);
        //将应用的appid注册到微信
        api.registerApp(Constants.APP_ID_WX);
        Logger
                .init("mytag")    //LOG TAG默认是PRETTYLOGGER
                .methodCount(3)                 // 决定打印多少行（每一行代表一个方法）默认：2
                .hideThreadInfo()               // 隐藏线程信息 默认：显示
                .logLevel(LogLevel.NONE)        // 是否显示Log 默认：LogLevel.FULL（全部显示）
                .methodOffset(2)                // 默认：0
                ; //可以自己构造适配器默认：AndroidLogAdapter
        //注意：
        //第三方开发者如果使用透明界面来实现WXEntryActivity，需要判断handleIntent的返回值，如果返回值为false，则说明入参不合法未被SDK处理，应finish当前透明界面，避免外部通过传递非法参数的Intent导致停留在透明界面，引起用户的疑惑
        try {
            boolean result =  api.handleIntent(getIntent(), this);
            if(!result){
//                Log.d("参数不合法，未被SDK处理，退出");
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        api.handleIntent(data,this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
        finish();
    }

    @Override
    public void onReq(BaseReq baseReq) {
//        ViseLog.d("baseReq:"+ JSON.toJSONString(baseReq));
    }

    @Override
    public void onResp(BaseResp baseResp) {
//        ViseLog.d("baseResp:"+JSON.toJSONString(baseResp));
//        ViseLog.d("baseResp:"+baseResp.errStr+","+baseResp.openId+","+baseResp.transaction+","+baseResp.errCode);
        String result = "";
        switch(baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                result ="发送成功";
                showMsg(1,result);
                try{
                    Gson gson=new Gson();
                    JSONObject  jsonObject=new JSONObject(gson.toJson(baseResp));
                   String code= jsonObject.optString("code");
                        if(!NullPointUtils.checknull(code)){
                            Toast.makeText(this, "已获取微信授权", Toast.LENGTH_SHORT).show();
                            new PrefApi(this, new VolleyInterface() {
                                @Override
                                public void onSuccess(String result) {
                                    try {
                                        JSONObject  jsonObject=new JSONObject(result);
                                        String access_token=jsonObject.optString("access_token");
                                        String openid=jsonObject.optString("openid");
                                        Toast.makeText(WXEntryActivity.this, "请求登录  token："+access_token+" id："+openid, Toast.LENGTH_SHORT).show();
                                        Log.e("srg","token："+access_token);
                                        Log.e("srg","id："+openid);
                                        Log.d("srg","token："+access_token);
                                        Log.d("srg","id："+openid);
                                        if(!NullPointUtils.checknull(access_token)){
                                            new LoginApi(  WXEntryActivity.this, new VolleyInterface() {
                                                @Override
                                                public void onSuccess(String result) {
                                                    try {
                                                        Log.d("srg","result"+result.toString());
                                                        JSONObject  jsonObject=new JSONObject(result);
                                                        if(jsonObject.optInt("result")==1){
                                                            PrefUtil.savePref(WXEntryActivity.this,"key",jsonObject.optString("data"));
                                                            Toast.makeText(WXEntryActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                                                            finish();
                                                        }else {
                                                            Toast.makeText(WXEntryActivity.this,"登录失败",Toast.LENGTH_SHORT).show();
                                                            finish();
                                                        }
                                                    } catch (JSONException e) {
                                                        e.printStackTrace();
                                                    }

                                                }

                                                @Override
                                                public void onError(VolleyError error) {

                                                }
                                            }).wxlogin(access_token,openid);
                                        }else {
                                            finish();
                                        }
                                    }catch (Exception e){
                                        e.printStackTrace();
                                        finish();
                                    }
                                }

                                @Override
                                public void onError(VolleyError error) {
                                    finish();
                                }
                            }).getwxinfo(code);
                        }else {
                            Toast.makeText(this, "未获取微信授权", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                }catch (Exception e){
                    e.printStackTrace();
                    finish();
                }

                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = "发送取消";
                showMsg(2,result);
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = "发送被拒绝";
                showMsg(1,result);
                finish();
                break;
            default:
                result = "发送返回";
                showMsg(0,result);
                finish();
                break;
        }

    }

    private void showMsg(int i, String result) {
    }
}
